<template>
  <van-popup
    v-model="state"
    position="right"
    closeable
    class="org-pick"
    :overlay="false"
    :style="{ height: '100vh', width: '100vw' }"
    get-container="body"
  >
    <div class="org-pick-nav">
      <van-icon name="hotel-o" />
      <HuBreadNav :nav.sync="breadNav" @onNav="onNav" :border="false" />
    </div>
    <span v-if="breadNav.length" class="blue preNext" @click="onPre">上一级</span>
    <div class="org-pick-list" :class="checkList.length ? 'org-pick-selected' : ''">
      <!-- 全选 -->
      <HuCheckCell
        v-if="multiple"
        :title="checkedAll ? '取消全选' : '全选'"
        :value="checkedAll"
        @clickCell="toggleAll"
      />
      <van-empty v-if="list.length === 0 && !loading" description="暂无数据" />
      <!-- 人员列表（图像+姓名 + 复选框） 组件 -->
      <HuCheckCell
        v-for="item in list"
        :key="item[defaultProps.id]"
        v-model="item.selected"
        :disabled="item.disabled"
        @clickCell="handleChange([item], item.selected)"
      >
        <template #title>
          <HuNameImg :portraitURL="item[defaultProps.avatar]" :name="item[defaultProps.name]" />
        </template>
        <template #value v-if="item && defaultProps && defaultProps.type && item[defaultProps.type] == 'dept'">
          <div class="blue cursor" @click.stop.prevent="handleNext(item)">下级</div>
        </template>
      </HuCheckCell>
    </div>

    <!-- 已选 -->
    <div class="org-pick-bottom">
      <HuCheckPopUp
        v-if="checkList.length > 0"
        :selecteds.sync="checkList"
        :props="defaultProps"
        @change="filterCheckList"
      />
      <!-- 确认 -->
      <van-button class="org-button--submit" @click="onConfirm">确认</van-button>
    </div>
  </van-popup>
</template>

<script>
import { requestUrl } from "@/api/data";
import defaultUser from "@/images/defaultUser.png";
import defaultUnit from "@/images/defaultUnit.png";
import { unionFun, differenceSetFun } from "@/components/formGenerator/utils";
import { deepClone } from "../../../utils/index";
import HuBreadNav from "../../../huComponents/HuBreadNav.vue";
import HuCheckPopUp from "../../../huComponents/HuCheckPopUp.vue";
import HuCheckCell from "../../../huComponents/HuCheckCell.vue";
import HuNameImg from "../../../huComponents/HuNameImg.vue";

export default {
  name: "OrgPicker",
  components: {
    HuBreadNav,
    HuCheckPopUp,
    HuCheckCell,
    HuNameImg,
  },
  props: {
    type: {
      default: "user", // org选择部门/人员  user-选人  dept-选部门 role-选角色
      type: String,
    },
    multiple: {
      // 是否多选
      default: false,
      type: Boolean,
    },
    data: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      state: false,
      list: [], // 已选中用户
      checkList: [],
      loading: false,
      checkedAll: false,
      breadNav: [], // 存储显示到面包屑导航中的数据
    };
  },
  computed: {
    requestProps() {
      return this.data.props.request || {};
    },
    responseProps() {
      return this.data.props.response || {};
    },
    defaultProps() {
      return {
        name: "name",
        id: "id",
        type: "type",
        portraitURL: this.responseProps.avatar,
        ...this.responseProps,
      };
    },
  },

  methods: {
    init() {
      this.checkList = [];
      this.breadNav = [];
      this.list = [];
      this.checkedAll = false;
    },
    open(checkList) {
      this.init();
      // 回显已选中数据
      if (checkList) {
        this.checkList = checkList.map((item) => {
          let obj = item;
          obj[this.defaultProps.avatar] = {
            dept: defaultUnit,
            user: defaultUser,
          }[item[this.defaultProps.type]];
          return obj;
        });
      }
      this.loadData();
      this.toggle();
    },

    toggle() {
      this.state = !this.state;
    },

    toggleAll(value) {
      const list = this.list.filter((item) => !item.disabled);
      this.handleChange(list, value);
    },
    // 下级
    handleNext(item) {
      // 将当前组织架构名存储在面包屑导航中
      this.breadNav.push({
        text: item[this.defaultProps.name],
        id: item[this.defaultProps.id],
      });
      this.breadNav = [...new Set(this.breadNav)];
      this.loadData(item[this.defaultProps.id]);
    },

    // 点击面包屑导航
    onNav(index, id) {
      this.loadData(id);
    },
    onPre() {
      this.breadNav.pop();
      const id = this.breadNav[this.breadNav.length - 1].id || "";
      this.loadData(id);
    },

    // 单独点击某个多选框/全选框
    // list-发生改变的单位数组，state-需要改变的状态 true-选中，false-取消选中
    handleChange(list, state) {
      if (!this.multiple) this.checkList = [];
      if (state) {
        // 并集即为选中
        this.checkList = unionFun(this.checkList, list, this.defaultProps.id);
      } else {
        // 差集即为取消选中
        this.checkList = differenceSetFun(
          this.checkList,
          list,
          this.defaultProps.id
        );
      }
      this.filterCheckList();
    },

    // 过滤当前选中
    filterCheckList() {
      // 在这里更新数据
      const checkedIds = this.checkList.map(
        (item) => item[this.defaultProps.id]
      );
      this.list.forEach((item) => {
        item.selected = false;
        if (checkedIds.includes(item[this.defaultProps.id]))
          item.selected = true;
      });
      this.$forceUpdate();
    },

    // 确认分享
    onConfirm() {
      const checkList = deepClone(this.checkList);
      checkList.forEach((item) => {
        delete item.selected;
      });
      this.$emit("callBack", checkList);
      this.$emit("update", checkList);
      this.toggle();
    },

    loadData(deptId) {
      let data = this.data.request;
      this.list = [];
      if (deptId) this.$set(data, this.requestProps.deptId, deptId);
      this.loading = true;
      requestUrl(this.data.url, this.data.method, data)
        .then((rsp) => {
          this.list = rsp.result.map((item) => {
            let obj = {
              ...item,
              disabled:
                item[this.defaultProps.type] !== "user" && this.type == "user",
            };
            obj[this.defaultProps.avatar] = {
              dept: defaultUnit,
              user: defaultUser,
            }[item && this.defaultProps && this.defaultProps.type ? item[this.defaultProps.type] : 'user'];
            return obj;
          });

          this.filterCheckList();
          if (this.data.response) {
            const func = new Function("response", this.data.response);
            func(rsp.result);
          }
        })
        .catch((err) => {
          if (this.data.error) {
            const func = new Function("error", this.data.error);
            func(err);
          }
        })
        .finally(() => {
          this.loading = false;
          this.finished = true;
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.org-button--submit {
  margin: 10px 20px;
  width: calc(100% - 40px);
  display: block;
  border-radius: 999px;
  background: linear-gradient(148deg, #478df4 0%, #42d0ea 100%);
  color: #fff;
  border: 0px;
}

.org-pick {
  overflow: hidden;
  .cursor {
    cursor: pointer;
  }
  .preNext {
    cursor: pointer;
    padding: 10px 16px;
    font-size: 12px;
  }
  .org-pick-list {
    height: calc(100% - 36px - 64px);
    overflow-y: auto;
    padding-bottom: 40px;
  }
  .org-pick-selected {
    height: calc(100% - 36px - 173px);
  }
  display: flex;
  flex-direction: column;
  .org-pick-bottom {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
  }
}
.org-pick-nav {
  position: relative;
  padding: 0 16px;
  padding-left: 36px;
  height: 36px;
  .van-icon {
    position: absolute;
    left: 16px;
    line-height: 36px;
  }
  .hu-bread-nav {
    padding-left: 0;
  }
}
</style>
